<template>
  <div class="vehicleManagement h100">
    <div class="PageContent">
      <div class="tablelist">
        <el-row style="text-align: left;line-height: 5em;">
          <el-button type="primary" plain v-if="btnRight.btnVehicleManagementAdd" @click="addCar()">添加</el-button>
          <el-button type="primary" v-if="btnRight.btnVehicleManagementEdit" @click="modifyCar()">修改</el-button>
          <el-button type="danger"  v-if="btnRight.btnVehicleManagementDelete" @click="removeCar()">删除</el-button>
        </el-row>
        <el-table
          ref="carTable"
          :data="tableCarData" :header-cell-style="{background:'rgb(246,247,251)',color:'#606266'}"
          border
          stripe
          @row-click="handleRowClick"
          @select="select" @selection-change="selectAll"
          style="width: 100%;height: calc(100% - 170px);overflow-y: scroll">
          <el-table-column
            type="selection"
            width="55">
          </el-table-column>
          <el-table-column
            property="carCode"
            label="车辆编号"
            align = 'center'
            width="120">
          </el-table-column>
          <el-table-column
            property="carNo"
            label="车牌号"
            align = 'center'
            width="120">
          </el-table-column>
          <el-table-column
            property="carType"
            label="车辆类别"
            align = 'center'
            width="120">
          </el-table-column>
          <el-table-column
            property="driverUserName"
            align = 'center'
            label="默认司机"
            width="120">
          </el-table-column>
          <el-table-column
            property="carBelong"
            align = 'center'
            label="车辆归属"
            width="120">
          </el-table-column>
          <el-table-column
            align = 'center'
            label="状态"
            width="120">
            <template slot-scope="{row,$index}">
              <p v-if="!row.disableState">
                <span>有效可用</span>
              </p>
              <p v-else>
                <span>无效禁用</span>
              </p>
            </template>
          </el-table-column>
          <el-table-column
            property="itemUnit"
            align = 'center'
            label="规则说明">
            <template slot-scope="{row,$index}" >
              <div v-if="row.ruleItems" v-for="(item, index) in row.ruleItems" :key="index">
                <p style="width: 100%;white-space: pre-wrap;">
                  <span>用途:【{{ item.purpose }}】,单价:【{{ item.itemPrice }}】,{{ item.ruleType }}，
                    {{ item.ruleDescribe }}</span>
                </p>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </div>
    <el-dialog title="车辆信息维护" :visible.sync="dialogVisibleCar" width="700px" v-dialogDrag   border >
      <el-form :model="saveCarData.car" class="saveform" :rules="rules"  ref="cardialog" :inline="true" label-width="120px" :disabled="saveFlagCar">
        <el-row :gutter="5">
          <el-form-item label="车辆编号:" prop="carCode">
            <el-input v-model="saveCarData.car.carCode" maxlength="50"></el-input>
          </el-form-item>
          <el-form-item label="车牌号:" prop="carNo">
            <el-input v-model="saveCarData.car.carNo"  maxlength="50"></el-input>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="车辆类别:" prop="carTypeCode">
            <el-select v-model="saveCarData.car.carTypeCode"
                       @change="carTypeChange(saveCarData.car.carTypeCode)"  placeholder="请选择" >
              <el-option
                v-for="item in saveCarData.dicts.transport_car_type	"
                :key="item.dataCode"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState?true:false"/>
            </el-select>
          </el-form-item>
          <el-form-item label="默认司机:" >
            <el-select v-model="saveCarData.car.driverUserId" filterable placeholder="请选择" >
              <el-option
                v-for="item in saveCarData.users.transport_task_driver_user"
                :key="item.id"
                :label="item.fullName"
                :value="item.id"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5" class="saveform" >
          <el-form-item label="收费规则:" >
            <div v-if="saveCarData.ruleItems"  class="ruleItem">
              <p class="content" v-for="(item, index) in showRule" :key="index">
                <span>用途:【{{ item.purpose }}】</span>，
                <span>单价:【{{ item.itemPrice }}】</span>，
                <span>{{ item.ruleType }}</span>，
                <span>{{ item.ruleDescribe }}</span>
              </p>
            </div>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="车辆归属:" prop="carBelongCode">
            <el-select v-model="saveCarData.car.carBelongCode"  placeholder="请选择" >
              <el-option
                v-for="item in saveCarData.dicts.car_belong	"
                :key="item.dataCode"
                :label="item.dataText"
                :value="item.dataCode"
                :disabled="item.disableState?true:false"/>
            </el-select>
          </el-form-item>
          <el-form-item label="状态:" prop="disableState">
            <el-select v-model="saveCarData.car.disableState" onkeydown="return (event.keyCode!=8)" placeholder="请选择" >
              <el-option
                v-for="item in disableState"
                :label="item.label"
                :value="item.value"/>
            </el-select>
          </el-form-item>
        </el-row>
        <el-row :gutter="5">
          <el-form-item label="显示顺序:" >
            <el-input onkeyup="value= (value.match(/^\d*(\.?\d{0,2})/g)[0]) || null"  v-model="saveCarData.car.sort"  maxlength="11"></el-input>
          </el-form-item>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: right;">
        <el-button type="primary" v-if="btnRight.btnVehicleManagementSave"  @click="saveCar()"  :disabled="saveFlagCar">保存</el-button>
        <el-button type="primary" plain v-if="btnRight.btnVehicleManagementCancel" @click="dialogVisibleCar = false">取 消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import * as API from '@/api/systemApplication'
  export default {
    name: "vehicleManagement",
    data() {
      let checkcarNo = (rule, value, callback) => {
        if(value){
          let patter = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵粤青藏川宁琼使领A-Z]{1}[A-Z]{1}[A-Z0-9]{4}[A-Z0-9挂学警港澳]{1}$/;;
          if(value.match(patter)==null){
            return callback(new Error('请输入正确的车牌号码'))
          }else{
            callback();
          }
        }
      };
      return {
        rules: {
          carCode: [
            {required: true, message: '请输入', trigger: 'blur'},
          ],
          carNo: [
            {required: true, message: '请输入', trigger: 'change'},
            {validator:checkcarNo,trigger:'change'}
          ],
          carTypeCode: [
            {required: true, message: '请选择', trigger: 'change'},
          ],
          carBelongCode: [
            {required: true, message: '请选择', trigger: 'change'},
          ],
          disableState: [
            {required: true, message: '请选择', trigger: 'change'},
          ],
        },
        //**车辆管理数据开始**//
        tableCarData: [],
        tableSelection:[],
        dialogVisibleCar:false,    //车辆对话框
        saveFlagCar:false,         //车辆保存标志
        onpresscTime:0,  //  阻止短时间内连续点击
        disableState:[
          {label:"有效可用",value:0},{label:"无效禁用",value:1},
        ],
        showRule:[], //根据车辆类型选择显示相应规则
        //车辆对话框需要数据
        saveCarData:{
          "car": {
            "id": 0,
            "carCode": "",
            "carNo": "",
            "carTypeCode": 0,
            "driverUserId": 0,
            "carBelongCode": 0,
            "disableState": 0,
            "sort": 0,
            "remark": "",
            "version": 0
          },
          "dicts": {
            "transport_car_type": [

            ],
            "car_belong": [

            ]
          },
          "users": {
            "transport_task_driver_user": []
          },
          "ruleItems": []
        },               //车辆

        btnRight: {
          btnVehicleManagementAdd: true, //添加
          btnVehicleManagementEdit: true,//修改
          btnVehicleManagementDelete: true,//删除
          btnVehicleManagementSave: true,//保存
          btnVehicleManagementCancel: true,//取消
        }
        //**车辆管理数据结束**//
      }
    },
    mounted(){
      this.loadCarListData();
      //载入按钮
      this.btnRight = this.$route.meta.buttons;
      //遍历属性赋值将true与false字符串转换成布尔型的值
      for (let key of Object.keys(this.btnRight)) {
        this.btnRight[key]=(this.btnRight[key]|| this.btnRight[key]=="true")?true:false;
      }
    },
    methods:{
      //全选
      selectAll(val) {
        this.multipleSelection = val;
      },
      /*//点击行触发，选中或不选中复选框
      handleRowClick(row, column, event) {
        if (this.tableSelection.length>0){
          this.$refs.carTable.toggleRowSelection(this.tableSelection[0],false);
        }
        this.$refs.carTable.toggleRowSelection(row);
        this.tableSelection = [row]
      },
      select(selection, row) {
        // 选择项大于1时
        if (selection.length > 1) {
          let del_row = selection.shift();
          // console.log('把数组的第一个元素从其中删除后', selection);
          this.$refs.carTable.toggleRowSelection(del_row, false); // 用于多选表格，切换某一行的选中状态，如果使用了第二个参数，则是设置这一行选中与否（selected 为 true 则选中）
        }
        this.tableSelection = selection
      },*/

      selectAll(selection) {
        if (selection.length >1) {
          selection.length = 1;
        }
        this.tableSelection = selection
      },
      /**********************车辆方法**********************/
      //table中类型添加
      addCar(){
        this.saveCarData.car = {
          "id": 0,
          "carCode": "",
          "carNo": "",
          "carTypeCode": "",
          "driverUserId": "",
          "carBelongCode": "",
          "disableState": "",
          "sort": "",
          "remark": "",
          "version": 0
        }

        let postData={
          "id": null,
          "dictTypeCodes": [
            "transport_car_type","car_belong"
          ],
          "userRoleCodes": [
            "transport_task_driver_user"
          ]
        }
        API['loadCarWithId'](postData).then(response=>{
          const { data }=response;
          if (!data) {
            this.$message('数据读取失败')
            return
          }
          if (data.dicts){
            this.saveCarData.dicts = data.dicts;
          }
          if (data.ruleItems){
            this.saveCarData.ruleItems = data.ruleItems;
          }
          if (data.users){
            this.saveCarData.users = data.users;
          }
          this.showRule = []
          if (this.saveCarData.car.carTypeCode) {
            this.saveCarData.ruleItems.forEach(item=>{
              if (item.dataCode == this.saveCarData.car.carTypeCode) {
                this.showRule.push(item)
              }
            })
          }
          this.dialogVisibleCar=true
        }).catch(error => {
          this.$message(error)
        })
        this.dialogVisibleCar = true
      },
      //table中类型修改
      modifyCar(){
        let data = this.tableSelection
        if (data.length==0) {
          this.$message("未选中车辆")
          return
        }
        let postData={
          "id": data[0].id,
          "dictTypeCodes": [
            "transport_car_type","car_belong"
          ],
          "userRoleCodes": [
            "transport_task_driver_user"
          ]
        }
        API['loadCarWithId'](postData).then(response=>{
          const { data }=response;
          if (!data) {
            this.$message('数据读取失败')
            return
          }
          if (data.car){
            this.saveCarData.car = data.car;
          }
          if (data.dicts){
            this.saveCarData.dicts = data.dicts;
          }
          if (data.ruleItems){
            this.saveCarData.ruleItems = data.ruleItems;
          }
          if (data.users){
            this.saveCarData.users = data.users;
          }
          this.showRule = []
          if (this.saveCarData.car.carTypeCode) {
            this.saveCarData.ruleItems.forEach(item=>{
              if (item.dataCode == this.saveCarData.car.carTypeCode) {
                this.showRule.push(item)
              }
            })
          }
          this.dialogVisibleCar=true
        }).catch(error => {
          this.$message(error)
        })
      },
      //table中服务物品类型删除
      removeCar(){
        let data = this.tableSelection
        if (data.length==0) {
          this.$message("未选中车辆")
          return
        }
        this.$confirm('删除信息, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let postData=[
            {
              "id": data[0].id,
              "version": data[0].version
            }
          ]
          API['deleteCarWithId'](postData).then(response=>{
            const { message }=response;
            this.$message(message)
            this.loadCarListData();
          }).catch(error => {
            this.$message(error)
          })
        }).catch(() => {
          //几点取消的提示
        });
      },

      //加载车辆列表
      loadCarListData(){
        let postData={
        }
        API['loadCarList'](postData).then(response=>{
          const { data }=response;
          debugger;
          if (!data) {
            this.$message('数据读取失败')
            return
          }
          debugger;
          this.tableCarData = data

        }).catch(error => {
          this.$message(error)
        })
      },
      //车辆类型改变后加载规则
      carTypeChange(id){
        this.showRule = []
        if (id) {
          this.saveCarData.ruleItems.forEach(item=>{
            if (item.dataCode == id) {
              this.showRule.push(item)
            }
          })
        }
      },
      //保存车辆信息
      saveCar(){
        if ((Date.now() - this.onpresscTime) > 2000) {
          this.onpresscTime = Date.now()
          console.log(Date.now())
        }else{
          return
        }
        this.$refs.cardialog.validate(valid=>{
          if (valid) {
            this.saveFlagCar = true
            let postData=this.saveCarData.car
            API['saveCar'](postData).then(response=>{
              const { message }=response;
              this.$message(message)
              this.loadCarListData()
              this.dialogVisibleCar=false
              this.saveFlagCar = false
            }).catch(error => {
              this.$message(error)
              this.saveFlagCar = false
            })
          }
        })
      },
      //验证整数
      onlySortNumber(){
        // 先把非数字的都替换掉，除了数字和.
        let obj=this.saveCarData.car.sort;
        obj=Number.parseInt(obj);
        this.saveCarData.car.sort=obj;
      }
      /**********************车辆方法**************************/
    },
    watch:{
      "dialogVisibleCar"(){
        if (this.dialogVisibleCar == false) {
          this.$nextTick(()=>{
            this.showRule = []
            this.$refs.cardialog.resetFields();
          })
        }
      }
    }
  }
</script>

<style scoped>
  .vehicleManagement{
    height: 100vh;
    background-color: red;
  }
  .content{
    width: 500px;
    display: inline-block;
  }
  .ruleItem{
    width: 532px;
    max-height: 6em;
    overflow-y: auto;
    line-height: 1.5em;
  }
  .ruleItem .content{
    width: 100%;
    padding-top:10px;
  }
</style>
